{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 验证数据集和交叉验证\n",
    "> Validation 和 Cross Validation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 为了防止我们仅针对测试数据集做优化，方向会被带偏，所以我们有分出了一部分数据作为验证集\n",
    "![测试数据集和验证数据集的作用](images/测试数据集和验证数据集的作用.png)\n",
    "## 为了防止随机数据导致的不确定性，训练集、验证集、测试集往往需要调换身份，即交叉验证\n",
    "![交叉验证](images/交叉验证.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from sklearn import datasets"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "digits = datasets.load_digits()\n",
    "X = digits.data\n",
    "y = digits.target"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 测试train_test_split"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=666)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Best K = 3\n",
      "Best P = 4\n",
      "Best Score = 0.9860917941585535\n"
     ]
    }
   ],
   "source": [
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "\n",
    "best_k, best_p, best_score = 0, 0, 0\n",
    "for k in range(2, 11):\n",
    "    for p in range(1, 6):\n",
    "        knn_clf = KNeighborsClassifier(weights=\"distance\", n_neighbors=k, p=p)\n",
    "        knn_clf.fit(X_train, y_train)\n",
    "        score = knn_clf.score(X_test, y_test)\n",
    "        if score > best_score:\n",
    "            best_k, best_p, best_score = k, p, score\n",
    "            \n",
    "print(\"Best K =\", best_k)\n",
    "print(\"Best P =\", best_p)\n",
    "print(\"Best Score =\", best_score)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 使用交叉验证"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0.98895028, 0.97777778, 0.96629213])"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sklearn.model_selection import cross_val_score # sklearn集成的交叉验证方法\n",
    "\n",
    "knn_clf = KNeighborsClassifier()\n",
    "cross_val_score(knn_clf, X_train, y_train, cv=3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Best K = 2\n",
      "Best P = 2\n",
      "Best Score = 0.9823599874006478\n"
     ]
    }
   ],
   "source": [
    "best_k, best_p, best_score = 0, 0, 0\n",
    "for k in range(2, 11):\n",
    "    for p in range(1, 6):\n",
    "        knn_clf = KNeighborsClassifier(weights=\"distance\", n_neighbors=k, p=p)\n",
    "        scores = cross_val_score(knn_clf, X_train, y_train, cv=3)\n",
    "        score = np.mean(scores)\n",
    "        if score > best_score:\n",
    "            best_k, best_p, best_score = k, p, score\n",
    "            \n",
    "print(\"Best K =\", best_k)\n",
    "print(\"Best P =\", best_p)\n",
    "print(\"Best Score =\", best_score) # 交叉验证得到的结果和上面非交叉验证得到的k和p不同，我们更相信交叉验证的"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.980528511821975"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "best_knn_clf = KNeighborsClassifier(weights=\"distance\", n_neighbors=2, p=2) # 参数详解见 https://www.cnblogs.com/pinard/p/6065607.html\n",
    "best_knn_clf.fit(X_train, y_train)\n",
    "best_knn_clf.score(X_test, y_test)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 回顾网格搜索\n",
    "> GridSearchCV本身内部已经实现了交叉验证"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Fitting 3 folds for each of 45 candidates, totalling 135 fits\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "D:\\ProgramData\\Anaconda3\\lib\\site-packages\\sklearn\\model_selection\\_split.py:1978: FutureWarning: The default value of cv will change from 3 to 5 in version 0.22. Specify it explicitly to silence this warning.\n",
      "  warnings.warn(CV_WARNING, FutureWarning)\n",
      "[Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers.\n",
      "[Parallel(n_jobs=1)]: Done 135 out of 135 | elapsed:   23.3s finished\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "GridSearchCV(cv='warn', error_score='raise-deprecating',\n",
       "             estimator=KNeighborsClassifier(algorithm='auto', leaf_size=30,\n",
       "                                            metric='minkowski',\n",
       "                                            metric_params=None, n_jobs=None,\n",
       "                                            n_neighbors=10, p=5,\n",
       "                                            weights='distance'),\n",
       "             iid='warn', n_jobs=None,\n",
       "             param_grid=[{'n_neighbors': [2, 3, 4, 5, 6, 7, 8, 9, 10],\n",
       "                          'p': [1, 2, 3, 4, 5], 'weights': ['distance']}],\n",
       "             pre_dispatch='2*n_jobs', refit=True, return_train_score=False,\n",
       "             scoring=None, verbose=1)"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sklearn.model_selection import GridSearchCV\n",
    "\n",
    "param_grid = [\n",
    "    {\n",
    "        'weights': ['distance'],\n",
    "        'n_neighbors': [i for i in range(2, 11)], \n",
    "        'p': [i for i in range(1, 6)]\n",
    "    }\n",
    "]\n",
    "\n",
    "grid_search = GridSearchCV(knn_clf, param_grid, verbose=1)\n",
    "grid_search.fit(X_train, y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.9823747680890538"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "grid_search.best_score_ # 最佳score"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'n_neighbors': 2, 'p': 2, 'weights': 'distance'}"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "grid_search.best_params_ # 最优参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.980528511821975"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "best_knn_clf = grid_search.best_estimator_\n",
    "best_knn_clf.score(X_test, y_test)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### cv参数\n",
    "> 训练数据集分成几份，默认是3份"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0.99543379, 0.96803653, 0.98148148, 0.96261682, 0.97619048])"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "cross_val_score(knn_clf, X_train, y_train, cv=5) # cv=5就返回了最佳的5个模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "grid_search = GridSearchCV(knn_clf, param_grid, verbose=1, cv=5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 交叉验证的常见方法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### k-folds交叉验证\n",
    "> 把训练数据集分成k份，称为k-folds cross validation\n",
    "\n",
    "缺点：每次训练k个模型，相当于整体性能满了k倍"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 留一法 LOO-CV\n",
    "> 把训练数据集分成m份，称为留一法 Leave-One-Out Cross Validation\n",
    "\n",
    "+ 优点：完全不受随机的影响，最接近模型真正的性能指标\n",
    "+ 缺点：计算量巨大"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
